package org.lsy.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.lsy.dao.AccountRepository;
import org.lsy.dao.TokenRepository;
import org.lsy.pojo.Account;
import org.lsy.pojo.Token;
import org.lsy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.UUID;

/**
 * @author liusy95
 * @version 1.0
 * @date 2020/7/29
 */
@Service
@Component
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private TokenRepository tokenRepository;

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public void register(String email, String password, HttpServletResponse response) {
        //保存账户
        Account account = new Account(email, password);
        accountRepository.save(account);
        //生成token并保存
        Token token = new Token(email, UUID.randomUUID().toString());
        tokenRepository.save(token);
        response.addCookie(cookieGenerator(token.getToken()));
    }

    @Override
    public boolean isRegistered(String email) {
        return accountRepository.existsByEmail(email);
    }

    @Override
    public String login(String email, String password, HttpServletResponse response) {
        //判断是否合法
        boolean exists = accountRepository.existsByEmailAndPassword(email, password);
        if (exists) {
            //生成token并保存
            Token token = new Token(email, UUID.randomUUID().toString());
            Token save = tokenRepository.save(token);
            response.addCookie(cookieGenerator(token.getToken()));
            return save.getEmail();
        } else {
            return "fail";
        }
    }

    @Override
    public String info(String token) {
        Token firstByToken = tokenRepository.findFirstByToken(token);
        return firstByToken == null ? "未找到对应email" : firstByToken.getEmail();
    }

    /**
     * 生成cookie
     * @param token token
     * @return 生成的cookie
     */
    private Cookie cookieGenerator(String token) {
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(5*60);
        cookie.setPath("/api");
        return cookie;
    }
}
